package com.leader.life.adapter

import android.content.Context
import android.content.Intent
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import com.leader.life.R
import com.leader.life.bean.MyBean
import com.leader.life.ext.isInstalled

class MyAdapter(context: Context, data: Array<MyBean>, layoutId: Int)
    : RecyclerView.Adapter<MyAdapter.MyVH>() {
    private val mContext = context
    private val mData = data
    private val layoutId = layoutId

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyVH {
        val view = LayoutInflater.from(mContext).inflate(layoutId, null, false)
        return MyVH(view)
    }

    override fun getItemCount(): Int = mData.size

    override fun onBindViewHolder(holder: MyVH, position: Int) {
        holder.btn.text = mData[position].title
        holder.btn.setOnClickListener {
            startUri(mData[position].uri)
        }
    }

    class MyVH(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val btn: Button = itemView.findViewById(R.id.btn)
    }

    /**
     * 启动 Uri
     */
    private fun startUri(uri: String) {
        if (mContext.isInstalled(uri)) {
            try {
                val intent = Intent.parseUri(uri, Intent.URI_INTENT_SCHEME)
                mContext.startActivity(intent)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }


}